package com.mflex.mwms.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.mflex.mwms.R;
import com.mflex.mwms.adapter.ShipmentOffDetailAdapter;
import com.mflex.mwms.model.CustomApiResult;
import com.mflex.mwms.model.ShipmentOffRequest;
import com.mflex.mwms.model.Task;
import com.mflex.mwms.model.TaskDetail;
import com.mflex.mwms.utils.MMKVUtils;
import com.mflex.mwms.utils.MessageUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ShipmentOffDetailActivity extends BaseActivity {
    @BindView(R.id.stv_TaskNo)
    EditText stvTaskNo;

    @BindView(R.id.stv_ShipmentId)
    EditText stvShipmentId;
    @BindView(R.id.stv_BoxNumber)
    EditText stvBoxNumber;

    @BindView(R.id.stv_BoxQty)
    EditText stvBoxQty;

    @BindView(R.id.stv_Address)
    EditText stvAddress;

    @BindView(R.id.stv_DateCode)
    EditText stvDateCode;

    @BindView(R.id.button_clear)
    Button buttonClear;

    @BindView(R.id.button_save)
    Button buttonSave;

    @BindView(R.id.lvTaskDetailList)
    ListView lvTaskDetailList;

    MiniLoadingDialog mMiniLoadingDialog;


    private Task task;

    List<TaskDetail> taskDetailList;

    private int scanBoxQty = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shipment_off_detail);
        ButterKnife.bind(this);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载...");

        Intent intent = getIntent();

        Type listType = new TypeToken<Task>() {
        }.getType();
        task = (Task) JsonUtil.fromJson(intent.getStringExtra("task"), listType);

        taskDetailList = task.getTaskDetails();
        Collections.sort(taskDetailList, new Comparator<TaskDetail>() {
            @Override
            public int compare(TaskDetail t0, TaskDetail t1) {
                if (t0.getDetailLocation().compareTo(t1.DetailLocation) > 0) {
                    return 1;
                } else if (t0.getDetailLocation().compareTo(t1.DetailLocation) == 0) {
                    return 0;
                } else {
                    return -1;
                }

            }
        });


        ShipmentOffDetailAdapter shipmentOffDetailAdapter = new ShipmentOffDetailAdapter(this, taskDetailList);
        lvTaskDetailList.setAdapter(shipmentOffDetailAdapter);

        stvTaskNo.setFocusable(false);
        stvTaskNo.setText(task.getTaskNo());

        stvShipmentId.setFocusable(false);
        stvShipmentId.setText(task.getStockoutDetails().get(0).getShipmentId());

        stvAddress.setText(task.getStockoutDetails().get(0).getAddressName());
        stvDateCode.setText(task.getStockoutDetails().get(0).getDateCode());

        stvBoxQty.setText(String.valueOf(scanBoxQty) + "/" + String.valueOf(task.getTaskDetails().size()));

        stvBoxNumber.setOnKeyListener(this);
//        stvShelfLocation.setOnKeyListener(this);
        buttonClear.setOnClickListener(this);
        buttonSave.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
//                clearButtonMd(view);
                setResult(0);
                finish();
                break;
            case R.id.button_save:
                saveButtonMd(view);

                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_BoxNumber:
                    CheckBoxNumber(view);
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    private void CheckBoxNumber(View view) {
        boolean flag = false;
        boolean existFlag = false;
        for (TaskDetail taskDetail : taskDetailList) {
            if (StringUtils.equals(stvBoxNumber.getText().toString(), taskDetail.getDetailName()) && taskDetail.checked) {
                existFlag = true;
                break;
            }
        }
        if (existFlag) {
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("箱号已在列表中")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(ShipmentOffDetailActivity.this, "箱号已在列表中");
            return;
        }
        for (TaskDetail taskDetail : taskDetailList) {
            if (StringUtils.equals(stvBoxNumber.getText().toString(), taskDetail.getDetailName())) {
                flag = true;
//                taskDetail.setChecked(true);
//                break;
            }
        }
        if (!flag) {
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("箱号不在该任务中")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(ShipmentOffDetailActivity.this, "箱号不在该任务中");
            stvBoxNumber.setText("");
            return;
        }
        scanBoxQty = scanBoxQty + 1;

        stvBoxQty.setText(String.valueOf(scanBoxQty) + "/" + String.valueOf(task.getTaskDetails().size()));
        for (TaskDetail taskDetail : taskDetailList) {
            if (StringUtils.equals(stvBoxNumber.getText().toString(), taskDetail.getDetailName())) {

                taskDetail.setChecked(true);
            }
        }

        Collections.sort(taskDetailList, new Comparator<TaskDetail>() {
            @Override
            public int compare(TaskDetail t0, TaskDetail t1) {
                if (!t0.isChecked() && t1.isChecked()) {
                    return -1;
                }
                return 0;
            }
        });

        ShipmentOffDetailAdapter shipmentOffDetailAdapter = new ShipmentOffDetailAdapter(ShipmentOffDetailActivity.this, taskDetailList);
        lvTaskDetailList.setAdapter(shipmentOffDetailAdapter);
        stvBoxNumber.setText("");
        stvBoxNumber.postDelayed(new Runnable() {
            @Override
            public void run() {
                stvBoxNumber.requestFocus();
            }
        }, 200);

//        ShipmentOffRequest shipmentOffRequest = new ShipmentOffRequest();
//        shipmentOffRequest.setBoxNumber(stvBoxNumber.getText().toString());
//        shipmentOffRequest.setTaskNo(taskNo);
//        shipmentOffRequest.setWarehouse(MMKVUtils.getString("Warehose", ""));
//        mMiniLoadingDialog.show();
//        XHttp.post("api/ShelfOff/ShipmentShelfOff")
//                .upJson(JsonUtil.toJson(shipmentOffRequest))
//                .syncRequest(false)
//                .onMainThread(true)
//                .accessToken(true)
//                .timeOut(120000)
//                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
//
//                    @Override
//                    public void onSuccess(String response) {
//                        mMiniLoadingDialog.dismiss();
//
//                        int count = 0;
//                        for (TaskDetail taskDetail : taskDetailList) {
//                            if (taskDetail.isChecked()) {
//                                count = count + 1;
//                            }
//                        }
//                        if (taskDetailList.size() == count + 1) {
//                            XToastUtils.success("全部下架成功", 2500);
//                            //最后一个
////                            setResult(0);
////                            finish();
//                        } else {
//                            XToastUtils.success("下架成功", 2500);
//                            for (TaskDetail taskDetail : taskDetailList) {
//                                if (StringUtils.equals(stvBoxNumber.getText().toString(), taskDetail.getDetailName())) {
//
//                                    taskDetail.setChecked(true);
//                                }
//                            }
//
//                            Collections.sort(taskDetailList, new Comparator<TaskDetail>() {
//                                @Override
//                                public int compare(TaskDetail t0, TaskDetail t1) {
//                                    if (!t0.isChecked() && t1.isChecked()) {
//                                        return -1;
//                                    }
//                                    return 0;
//                                }
//                            });
//
//                            ShipmentOffDetailAdapter shipmentOffDetailAdapter = new ShipmentOffDetailAdapter(ShipmentOffDetailActivity.this, taskDetailList);
//                            lvTaskDetailList.setAdapter(shipmentOffDetailAdapter);
//                            stvBoxNumber.setText("");
//                            stvBoxNumber.postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    stvBoxNumber.requestFocus();
//                                }
//                            }, 200);
//                        }
//                    }
//
//                    @Override
//                    public void onError(ApiException e) {
//                        mMiniLoadingDialog.dismiss();
//                        stvBoxNumber.setText("");
//                        stvBoxNumber.requestFocus();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(view.getContext())
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(view.getContext())
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                    }
//                }) {
//                });


    }

    private void clearButtonMd(View v) {
        stvBoxNumber.setText("");
//        stvShelfLocation.setText("");
//        stvShelfLocation.requestFocus();
        taskDetailList = new ArrayList<>();
        ShipmentOffDetailAdapter shipmentOffDetailAdapter = new ShipmentOffDetailAdapter(this, taskDetailList);
        lvTaskDetailList.setAdapter(shipmentOffDetailAdapter);
    }

    private void saveButtonMd(View v) {
        boolean flag = false;
        List<String> boxs = new ArrayList<>();
        for (TaskDetail taskDetail : taskDetailList) {
            if (taskDetail.isChecked()) {
                flag = true;
                boxs.add(taskDetail.getDetailName());
            }
        }
        if (!flag) {
//            new MaterialDialog.Builder(v.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("提交列表为空")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(ShipmentOffDetailActivity.this, "提交列表为空");
            return;
        }



        ShipmentOffRequest shipmentOffRequest = new ShipmentOffRequest();
        shipmentOffRequest.setBoxNumbers(boxs);
        shipmentOffRequest.setTaskNo(task.getTaskNo());
        shipmentOffRequest.setWarehouse(MMKVUtils.getString("Warehose", ""));
        mMiniLoadingDialog.show();
        XHttp.post("api/ShelfOff/ShipmentShelfOffNew")
                .upJson(JsonUtil.toJson(shipmentOffRequest))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(500000)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {

                    @Override
                    public void onSuccess(String response) {
                        mMiniLoadingDialog.dismiss();
                        setResult(0);
                        finish();
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        stvBoxNumber.setText("");
                        stvBoxNumber.requestFocus();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(ShipmentOffDetailActivity.this)
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(ShipmentOffDetailActivity.this)
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(ShipmentOffDetailActivity.this, e);
                    }
                }) {
                });


    }
}